package com.umeox.auto_light

import com.umeox.logger.UMLogger
import com.umeox.sdk_ring.UMRingSdk
import com.umeox.sdk_ring.protocol.IEmptyAppProtocol
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.Date
import java.util.TimeZone
import kotlin.math.abs

class DeviceProxy(val device: Device) : IEmptyAppProtocol {

    companion object {
        const val STATE_IDLE = 0
        const val STATE_SUCCESS = 2
        const val STATE_ERROR = 3
    }

    /**
     * 设备携程空间
     */
    private val deviceScope =
        CloseableCoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    private val record = arrayListOf<String>()

    /**
     * 当前设备状态
     */
    var state = STATE_IDLE

    fun getDeviceInfo(): String {
        return record.joinToString("->")
    }

    private val ringProxy by lazy {
        UMRingSdk.createRingProxy(device.mac).apply {
            addAppProtocolObserver(this@DeviceProxy)
        }
    }

    fun startTask() {
        record.add("开始任务")
        UMLogger.d(
            TAG,
            "设备${device.name} - ${device.mac} - ${device.rssi}开始任务"
        )
        ringProxy.directConnectDevice()
    }

    override fun onConnectTimeout() {
        record.add("连接超时")
        UMLogger.d(
            TAG,
            "设备${device.name} - ${device.mac} - ${device.rssi}设备连接超时"
        )
        onFailed()
    }

    override fun onConnected() {
        record.add("连接成功")
        UMLogger.d(
            TAG,
            "设备${device.name} - ${device.mac} - ${device.rssi}连接成功"
        )

        deviceScope.launch {
            delay(1000)
            record.add("发送全亮屏指令")
            UMLogger.d(
                TAG,
                "设备${device.mac}发送全亮屏指令"
            )
            ringProxy.n01ScreenTest(true)
            onSuccess()
        }
    }

    override fun requestTimeSync() {
        ringProxy.syncCurrentTimeAndTimeFormat(null, null, true, getCurrentTimeZone())
    }

    /**
     * 可简化计算过程 为了方便理解 没有简化
     */
    private fun getCurrentTimeZone(): Double {
        val now = Date()
        val zone = TimeZone.getDefault()
        val id = zone.id
        val timeZone1 = TimeZone.getTimeZone(id)
        val timeZone2 = TimeZone.getTimeZone("UTC")

        val currentOffsetFromUTC = if (timeZone1.inDaylightTime(now)) {
            timeZone1.dstSavings + timeZone1.rawOffset
        } else {
            0 + timeZone1.rawOffset
        }

        val serverOffsetFromUTC = if (timeZone2.inDaylightTime(now)) {
            timeZone2.dstSavings + timeZone2.rawOffset
        } else {
            0 + timeZone2.rawOffset
        }

        val isNegativeNumber = currentOffsetFromUTC < 0

        val secondOffset = abs(abs(serverOffsetFromUTC) - currentOffsetFromUTC) / 1000
        val hour = secondOffset / 3600
        val minute = secondOffset % 3600 / 60
        return if (isNegativeNumber) {
            -1.0 * (hour + minute / 60.0)
        } else {
            hour + minute / 60.0
        }
    }

    private fun onSuccess() {
        //升级成功
        record.add("已发送全亮屏指令")
        UMLogger.d(
            TAG,
            "设备${device.mac} 已发送全亮屏指令"
        )
        deviceScope.launch {
            delay(1000)
            ringProxy.destroy()
            delay(1000)
            state = STATE_SUCCESS
            DeviceListManager.finishDeviceTaskAndStartNextIfNeed()
        }
    }

    private fun onFailed() {
        deviceScope.launch(Dispatchers.Main) {
            state = STATE_ERROR
            record.add("销毁")
            UMLogger.d(
                TAG,
                "销毁设备${device.mac}"
            )
            ringProxy.destroy()
            delay(3000)
            DeviceListManager.finishDeviceTaskAndStartNextIfNeed()
        }
    }
}